package com.next.aappublicapp.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;

import com.next.aappublicapp.AapApplication;
import com.next.aappublicapp.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

public class ImageUtil {

	private static DisplayImageOptions options;
	{
		DisplayImageOptions.Builder optionBuilder = new DisplayImageOptions.Builder();
		optionBuilder.showStubImage(R.drawable.image_not_available);
		optionBuilder.showImageForEmptyUri(R.drawable.image_not_available);
		optionBuilder.showImageOnFail(R.drawable.image_not_available);
		//optionBuilder.cacheInMemory();
		optionBuilder.cacheOnDisc();
		//Options decodeOption = new Options();
		
		//optionBuilder.decodingOptions(decodingOptions)
		optionBuilder.bitmapConfig(Bitmap.Config.RGB_565);
		options = optionBuilder.build();
	}
	public static DisplayImageOptions getDisplayImageOptions(){
		return options;
	}
	/**
     * Copies a private raw resource content to a publicly readable
     * file such that the latter can be shared with other applications.
     */
	public static void copyPrivateRawResourceToPubliclyAccessibleFile(Context context,ImageView imageView) {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
        	BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
        	Bitmap bitmap = bitmapDrawable.getBitmap();
        	ByteArrayOutputStream stream = new ByteArrayOutputStream();
        	bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        	byte[] imageInByte = stream.toByteArray();
        	inputStream = new ByteArrayInputStream(imageInByte);
        	
            outputStream = context.openFileOutput(AapApplication.SHARED_FILE_NAME,
                    Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
            byte[] buffer = new byte[1024];
            int length = 0;
            try {
                while ((length = inputStream.read(buffer)) > 0){
                    outputStream.write(buffer, 0, length);
                }
            } catch (IOException ioe) {
                /* ignore */
            }
        } catch (FileNotFoundException fnfe) {
            /* ignore */
        } finally {
            try {
                inputStream.close();
            } catch (IOException ioe) {
               /* ignore */
            }
            try {
                outputStream.close();
            } catch (IOException ioe) {
               /* ignore */
            }
        }
    }
}
